package Tools;

import DataManage.AddDatabase;
import DataManage.AddFile;
import Finish.SearchAddr;
import com.google.common.base.Utf8;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;

public class HttpRequest {
    private HttpPost httpPost;
    private CloseableHttpResponse response;
    private CloseableHttpClient httpclient;
    private HttpEntity entity;
    private String result;
    private HttpGet httpGet;
    SearchAddr search = new SearchAddr();
    AddDatabase add = new AddDatabase();
    String Result;

    public HttpRequest() {
        //创建默认httpclent实例
        httpclient = HttpClients.createDefault();
    }

    public String sendPost(String url,List<NameValuePair> content, String interfaceName, String path){
        httpPost=new HttpPost(url);//实例化httppost（）
        RequestConfig config=RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();//设置请求和传输超市时间
        httpPost.setConfig(config);
        try {
            //记录发送请求时的时间
            long requestTime = System.currentTimeMillis();
            HttpEntity entity = new UrlEncodedFormEntity(content,HTTP.UTF_8);//设置请求编码为utf8
            httpPost.setEntity(entity);
            response=httpclient.execute(httpPost);
            entity=response.getEntity();
            int rescode = response.getStatusLine().getStatusCode();//获取返回状态码、
            //状态码校验，200为成功
            if(rescode == 200){
                String charset = "UTF-8";
                result= EntityUtils.toString(entity,charset);
            }
            else{
                result = "{\"msg\":\"返回状态码为 "+rescode+" ,链接访问错误！\"}";
            }
            //记录服务器返回响应值时的时间
            long responseTime = System.currentTimeMillis();
            String time = String.valueOf(responseTime - requestTime)+"ms";
            System.out.println("响应时间为：" + time + "ms");
            String request = url+content;
            String code = search.findcode(result);
            switch (interfaceName){
                case "好友申请/B同意所有申请":
                    if(code.equals("10257")){
                        Result = "true";
                    }else{
                        Result = "false";
                    }
                    break;

                case "注册/手机注册接口1500":
                    if(code.equals("10002")){
                        Result = "true";
                    }else{
                        Result = "false";
                    }
                    break;

                case "注册/手机注册接口1326":
                    if(code.equals("10003")){
                        Result = "true";
                    }else{
                        Result = "false";
                    }
                    break;

                default:
                    if (code.equals("200")) {
                        Result = "true";
                    } else {
                        Result = "false";
                    }
                    break;
            }
            /*if (interfaceName.equals("好友申请/B同意所有申请")){
                if(code.equals("10257")){
                    Result = "true";
                }else{
                    Result = "false";
                }
            }
            else if (interfaceName.equals("注册/手机注册接口1500")){ // 判断已注册手机接口逻辑
                if(code.equals("10002")){
                    Result = "true";
                }else{
                    Result = "false";
                }
            }
            else if (interfaceName.equals("注册/手机注册接口1326")){ //判断手机验证码输入错误接口逻辑
                if(code.equals("10003")){
                    Result = "true";
                }else{
                    Result = "false";
                }
            }
            else { //除特殊情况外所有正常情况
                if (code.equals("200")) {
                    Result = "true";
                } else {
                    Result = "false";
                }
            }*/
            String coderesult = "[code: "+code+"]";
            add.adddatabase(interfaceName,path,request,coderesult,time,Result);
            System.out.println(result);

        }
        catch (IOException e) {
            System.out.println("ERROR：数据流异常！"+url);
            result = e.getMessage();
            //e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return result;

    }

    //分享二维码的content中含有双引号，sql语句会报错，所以需要强制转义
    public String sendPostqrshare(String url,List<NameValuePair> content, String interfaceName, String path,String token,String groupid,String toUserCubes){
        httpPost=new HttpPost(url);//实例化httppost（）
        RequestConfig config=RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();//设置请求和传输超市时间
        httpPost.setConfig(config);
        try {
            //记录发送请求时的时间
            long requestTime = System.currentTimeMillis();
            httpPost.setEntity(new UrlEncodedFormEntity(content));
            response=httpclient.execute(httpPost);
            entity=response.getEntity();
            int rescode = response.getStatusLine().getStatusCode();//获取返回状态码、
            //状态码校验，200为成功
            if(rescode == 200){
                String charset = "UTF-8";
                result= EntityUtils.toString(entity,charset);
            }
            else{
                result = "{\"msg\":\"返回状态码为 "+rescode+" ,链接访问错误！\"}";
            }
            //记录服务器返回响应值时的时间
            long responseTime = System.currentTimeMillis();
            String time = String.valueOf(responseTime - requestTime)+"ms";
            System.out.println("响应时间为：" + time + "ms");

            String code = search.findcode(result);
            if(code.equals("200")){
                Result = "true";
            }else{
                Result = "false";
            }
            String coderesult = "[code: "+code+"]";
            add.adddatabase(interfaceName,path,url+path+"[token="+token+", groupId="+groupid+", toUserCubes="+toUserCubes+"]",coderesult,time,Result);
            System.out.println(result);

        }
        catch (IOException e) {
            System.out.println("ERROR：数据流异常！"+url);
            result = e.getMessage();
            //e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return result;

    }

    //个人资料更新个人信息的content中含有双引号，sql语句会报错，所以需要强制转义
    public String sendPostupdateinfo(String url,List<NameValuePair> content, String interfaceName, String path,String token,String nickname,String displayName,String sex,String birthday,String phone,String email,String company,String job,String area,String industry,String groupVerify){
        httpPost=new HttpPost(url);//实例化httppost（）
        RequestConfig config=RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();//设置请求和传输超市时间
        httpPost.setConfig(config);
        try {
            //记录发送请求时的时间
            long requestTime = System.currentTimeMillis();
            httpPost.setEntity(new UrlEncodedFormEntity(content));
            response=httpclient.execute(httpPost);
            entity=response.getEntity();
            int rescode = response.getStatusLine().getStatusCode();//获取返回状态码、
            //状态码校验，200为成功
            if(rescode == 200){
                String charset = "UTF-8";
                result= EntityUtils.toString(entity,charset);
            }
            else{
                result = "{\"msg\":\"返回状态码为 "+rescode+" ,链接访问错误！\"}";
            }
            //记录服务器返回响应值时的时间
            long responseTime = System.currentTimeMillis();
            String time = String.valueOf(responseTime - requestTime)+"ms";
            System.out.println("响应时间为：" + time + "ms");

            String code = search.findcode(result);
            if(code.equals("200")){
                Result = "true";
            }else{
                Result = "false";
            }
            String coderesult = "[code: "+code+"]";
            add.adddatabase(interfaceName,path,url+path+"[token="+token+", nickname="+nickname+", displayName="+displayName+", sex="+sex+", birthday="+birthday+
                    ", phone="+phone+", email="+email+", company="+company+", job="+job+", area="+area+", industry="+industry+", groupVerify="+groupVerify+"]",coderesult,time,Result);
            System.out.println(result);

        }
        catch (IOException e) {
            System.out.println("ERROR：数据流异常！"+url);
            result = e.getMessage();
            //e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return result;

    }

    //导入联系人中的contacts含有双引号，sql语句会报错，所以需要强制转义
    public String sendPostcontacts(String url,List<NameValuePair> content, String interfaceName, String path,String token,String contacts){
        httpPost=new HttpPost(url);//实例化httppost（）
        RequestConfig config=RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();//设置请求和传输超市时间
        httpPost.setConfig(config);
        try {
            //记录发送请求时的时间
            long requestTime = System.currentTimeMillis();
            httpPost.setEntity(new UrlEncodedFormEntity(content));
            response=httpclient.execute(httpPost);
            entity=response.getEntity();
            int rescode = response.getStatusLine().getStatusCode();//获取返回状态码、
            //状态码校验，200为成功
            if(rescode == 200){
                String charset = "UTF-8";
                result= EntityUtils.toString(entity,charset);
            }
            else{
                result = "{\"msg\":\"返回状态码为 "+rescode+" ,链接访问错误！\"}";
            }
            //记录服务器返回响应值时的时间
            long responseTime = System.currentTimeMillis();
            String time = String.valueOf(responseTime - requestTime)+"ms";
            System.out.println("响应时间为：" + time + "ms");

            String code = search.findcode(result);
            if(code.equals("200")){
                Result = "true";
            }else{
                Result = "false";
            }
            String coderesult = "[code: "+code+"]";
            add.adddatabase(interfaceName,path,url+path+"[token="+token+", contacts="+contacts+"]",coderesult,time,Result);
            System.out.println(result);

        }
        catch (IOException e) {
            System.out.println("ERROR：数据流异常！"+url);
            result = e.getMessage();
            //e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return result;

    }

    //获取天气中含有双引号，sql语句会报错，所以需要强制转义
    public String sendPostweather(String url,List<NameValuePair> content, String interfaceName, String path,String token,String province,String city,String county){
        httpPost=new HttpPost(url);//实例化httppost（）
        RequestConfig config=RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();//设置请求和传输超市时间
        httpPost.setConfig(config);
        try {
            //记录发送请求时的时间
            long requestTime = System.currentTimeMillis();
            HttpEntity entity = new UrlEncodedFormEntity(content,HTTP.UTF_8);//设置请求编码为utf8
            httpPost.setEntity(entity);
            response=httpclient.execute(httpPost);
            entity=response.getEntity();
            int rescode = response.getStatusLine().getStatusCode();//获取返回状态码、
            //状态码校验，200为成功
            if(rescode == 200){
                String charset = "UTF-8";
                result= EntityUtils.toString(entity,charset);
            }
            else{
                result = "{\"msg\":\"返回状态码为 "+rescode+" ,链接访问错误！\"}";
            }
            //记录服务器返回响应值时的时间
            long responseTime = System.currentTimeMillis();
            String time = String.valueOf(responseTime - requestTime)+"ms";
            System.out.println("响应时间为：" + time + "ms");

            String code = search.findcode(result);
            if(code.equals("200")){
                Result = "true";
            }else{
                Result = "false";
            }
            String coderesult = "[code: "+code+"]";
            add.adddatabase(interfaceName,path,url+path+"[token="+token+", province="+province+", city="+city+", county="+county+"]",coderesult,time,Result);
            System.out.println(result);

        }
        catch (IOException e) {
            System.out.println("ERROR：数据流异常！"+url);
            result = e.getMessage();
            //e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return result;

    }

    public String sendGet(String url, String interfaceName, String path) {

        //String result = null;
        httpGet = new HttpGet(url);
        RequestConfig config=RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();//设置请求和传输超时时间
        httpGet.setConfig(config);
        try {
            //记录发送请求时的时间
            long requestTime = System.currentTimeMillis();
            response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            int rescode = response.getStatusLine().getStatusCode();//获取返回状态码
            //状态码校验，200为成功
            if(rescode == 200){
                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    result =  line;
                }
            }
            else{
                result = "{\"msg\":\"返回状态码为 "+rescode+" ,链接访问错误！\"}";
            }
            //记录服务器返回响应值时的时间
            long responseTime = System.currentTimeMillis();
            String time = String.valueOf(responseTime - requestTime);
            System.out.println("响应时间为：" + time + "ms");

            String request = url;
            String code = search.findcode(result);
            if(code.equals("200")){
                Result = "true";
            }else{
                Result = "false";
            }
            String coderesult = "[code: "+code+"]";
            add.adddatabase(interfaceName,path,request,coderesult,time,Result);

        } catch (ClientProtocolException e) {
            System.out.println("ERROR：客户端协议异常！"+url);
            result = e.getMessage();
        } catch (IOException e) {
            System.out.println("ERROR：数据流异常！"+url);
            result = e.getMessage();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println(url);
        System.out.println(result);


        return result;
    }


    public static String updategroup(File file, String url, String token,String groupid, String interfacename, String path) throws ClientProtocolException, IOException, SQLException, ClassNotFoundException {
        String result;

        FileBody bin = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        if (file != null) {
            bin = new FileBody(file);
        }

        StringBody username = new StringBody(token);
        StringBody groupId = new StringBody(groupid);
        //StringBody password = new StringBody("13696900475");

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("token", username);
        reqEntity.addPart("groupId",groupId);
        //reqEntity.addPart("password", password);
        reqEntity.addPart("faceImage", bin);
        //记录发送请求时的时间
        long requestTime = System.currentTimeMillis();
        httppost.setEntity(reqEntity);
        System.out.println("执行: " + httppost.getRequestLine());

        HttpResponse response = httpclient.execute(httppost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            String charset = "UTF-8";
            result = EntityUtils.toString(response.getEntity(), charset);
        } else {
            result = "{\"msg\":\"返回状态码为：" + statusCode + ",链接访问错误！\"}";
        }
        //System.out.println("statusCode is " + response.getStatusLine().getStatusCode());
        //记录服务器返回响应值时的时间
        long responseTime = System.currentTimeMillis();
        String time = String.valueOf(responseTime - requestTime)+"ms";
        System.out.println("响应时间为：" + time + "ms");
        System.out.println(result);
        String request = url+reqEntity;
        String Result;
        AddDatabase add = new AddDatabase();
        SearchAddr search = new SearchAddr();
        String code = search.findcode(result);
        if(code.equals("200")){
            Result = "true";
        }else{
            Result = "false";
        }
        String coderesult = "[code: "+code+"]";
        add.adddatabase(interfacename,path,request,coderesult,time,Result);
        HttpEntity resEntity = response.getEntity();
        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("返回长度: " + resEntity.getContentLength());
            System.out.println("返回类型: " + resEntity.getContentType());
            InputStream in = resEntity.getContent();
            System.out.println("in is " + in);
            //System.out.println(IoStreamUtil.getStringFromInputStream(in));
        }
        if (resEntity != null) {
            resEntity.consumeContent();
        }
        return result;
    }

    //举报群组
    public static String complaintsgroup(File file, String url, String token,String groupid, String interfacename, String path, String complainttypes, String content) throws ClientProtocolException, IOException, SQLException, ClassNotFoundException {
        String result;

        FileBody bin = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        if (file != null) {
            bin = new FileBody(file);
        }

        StringBody username = new StringBody(token);
        StringBody groupId = new StringBody(groupid);
        StringBody complainttype = new StringBody(complainttypes);
        StringBody contents = new StringBody(content);
        //StringBody password = new StringBody("13696900475");

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("token", username);
        reqEntity.addPart("groupId",groupId);
        reqEntity.addPart("complaintTypes",complainttype);
        reqEntity.addPart("content",contents);
        //reqEntity.addPart("password", password);
        reqEntity.addPart("images", bin);
        //记录发送请求时的时间
        long requestTime = System.currentTimeMillis();
        httppost.setEntity(reqEntity);
        System.out.println("执行: " + httppost.getRequestLine());

        HttpResponse response = httpclient.execute(httppost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            String charset = "UTF-8";
            result = EntityUtils.toString(response.getEntity(), charset);
        } else {
            result = "{\"msg\":\"返回状态码为：" + statusCode + ",链接访问错误！\"}";
        }
        //System.out.println("statusCode is " + response.getStatusLine().getStatusCode());
        //记录服务器返回响应值时的时间
        long responseTime = System.currentTimeMillis();
        String time = String.valueOf(responseTime - requestTime)+"ms";
        System.out.println("响应时间为：" + time + "ms");
        System.out.println(result);
        String request = url+reqEntity;
        String Result;
        AddDatabase add = new AddDatabase();
        SearchAddr search = new SearchAddr();
        String code = search.findcode(result);
        if(code.equals("200")){
            Result = "true";
        }else{
            Result = "false";
        }
        String coderesult = "[code: "+code+"]";
        add.adddatabase(interfacename,path,request,coderesult,time,Result);
        HttpEntity resEntity = response.getEntity();
        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("返回长度: " + resEntity.getContentLength());
            System.out.println("返回类型: " + resEntity.getContentType());
            InputStream in = resEntity.getContent();
            System.out.println("in is " + in);
            //System.out.println(IoStreamUtil.getStringFromInputStream(in));
        }
        if (resEntity != null) {
            resEntity.consumeContent();
        }
        return result;
    }

    //举报个人
    public static String complaintsuser(File file, String url, String token,String userid, String interfacename, String path, String complainttypes, String content) throws ClientProtocolException, IOException, SQLException, ClassNotFoundException {
        String result;

        FileBody bin = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        if (file != null) {
            bin = new FileBody(file);
        }

        StringBody username = new StringBody(token);
        StringBody userId = new StringBody(userid);
        StringBody complainttype = new StringBody(complainttypes);
        StringBody contents = new StringBody(content);
        //StringBody password = new StringBody("13696900475");

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("token", username);
        reqEntity.addPart("userId",userId);
        reqEntity.addPart("complaintTypes",complainttype);
        reqEntity.addPart("content",contents);
        //reqEntity.addPart("password", password);
        reqEntity.addPart("images", bin);
        //记录发送请求时的时间
        long requestTime = System.currentTimeMillis();
        httppost.setEntity(reqEntity);
        System.out.println("执行: " + httppost.getRequestLine());

        HttpResponse response = httpclient.execute(httppost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            String charset = "UTF-8";
            result = EntityUtils.toString(response.getEntity(), charset);
        } else {
            result = "{\"msg\":\"返回状态码为：" + statusCode + ",链接访问错误！\"}";
        }
        //System.out.println("statusCode is " + response.getStatusLine().getStatusCode());
        //记录服务器返回响应值时的时间
        long responseTime = System.currentTimeMillis();
        String time = String.valueOf(responseTime - requestTime)+"ms";
        System.out.println("响应时间为：" + time + "ms");
        System.out.println(result);
        String request = url+reqEntity;
        String Result;
        AddDatabase add = new AddDatabase();
        SearchAddr search = new SearchAddr();
        String code = search.findcode(result);
        if(code.equals("200")){
            Result = "true";
        }else{
            Result = "false";
        }
        String coderesult = "[code: "+code+"]";
        add.adddatabase(interfacename,path,request,coderesult,time,Result);
        HttpEntity resEntity = response.getEntity();
        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("返回长度: " + resEntity.getContentLength());
            System.out.println("返回类型: " + resEntity.getContentType());
            InputStream in = resEntity.getContent();
            System.out.println("in is " + in);
            //System.out.println(IoStreamUtil.getStringFromInputStream(in));
        }
        if (resEntity != null) {
            resEntity.consumeContent();
        }
        return result;
    }

    public static String postFile(File file, String url, String token, String interfacename, String path) throws ClientProtocolException, IOException, SQLException, ClassNotFoundException {
        String result;
        FileBody bin = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        if (file != null) {
            bin = new FileBody(file);
        }

        StringBody username = new StringBody(token);
        //StringBody password = new StringBody("13696900475");

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("token", username);
        //reqEntity.addPart("password", password);
        reqEntity.addPart("faceImage", bin);

        //记录发送请求时的时间
        long requestTime = System.currentTimeMillis();
        httppost.setEntity(reqEntity);
        System.out.println("执行: " + httppost.getRequestLine());

        HttpResponse response = httpclient.execute(httppost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            String charset = "UTF-8";
            result = EntityUtils.toString(response.getEntity(), charset);
        } else {
            result = "{\"msg\":\"返回状态码为：" + statusCode + ",链接访问错误！\"}";
        }
        //记录服务器返回响应值时的时间
        long responseTime = System.currentTimeMillis();
        String time = String.valueOf(responseTime - requestTime)+"ms";
        System.out.println("响应时间为：" + time + "ms");
        //System.out.println("statusCode is " + response.getStatusLine().getStatusCode());
        System.out.println(result);

        String request = url+reqEntity;
        String Result;
        AddDatabase add = new AddDatabase();
        SearchAddr search = new SearchAddr();
        String code = search.findcode(result);
        if(code.equals("200")){
            Result = "true";
        }else{
            Result = "false";
        }
        String coderesult = "[code: "+code+"]";
        add.adddatabase(interfacename,path,request,coderesult,time,Result);

        HttpEntity resEntity = response.getEntity();
        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("返回长度: " + resEntity.getContentLength());
            System.out.println("返回类型: " + resEntity.getContentType());
            InputStream in = resEntity.getContent();
            System.out.println("in is " + in);
            //System.out.println(IoStreamUtil.getStringFromInputStream(in));
        }
        if (resEntity != null) {
            resEntity.consumeContent();
        }
        return result;
    }
}
